Method Overriding is a feature in Java’s Object-Oriented Programming (OOP) that allows a subclass to provide a specific implementation of a method that is already provided by its superclass. This is one of the ways Java achieves Runtime Polymorphism.
Here are some key points about method overriding:
-> If a subclass has the same method as declared in the parent class, it is known as method overriding.
-> Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
-> The method in the subclass is said to override the method in the superclass.
-> The method must have the same name, parameters, and return type as in the parent class.
-> There must be an IS-A relationship (inheritance) between the classes.
Here’s an example of method overriding in Java:
Example of method overriding in java
// Superclass
class Animal {
void eat() {
System.out.println("Animal is eating...");
}
}
// Subclass
class Dog extends Animal {
@Override
void eat() {
System.out.println("Dog is eating...");
}
}
public class Main {
public static void main(String args[]) {
Dog d = new Dog();
d.eat();
}
}
Output
Dog is barking...
Animal is eating...
In this example, Dog is a subclass that extends the Animal superclass. The Dog class overrides the eat() method from the Animal class.
There are some rules for method overriding in Java:
Overriding and Access Modifiers: The access modifier for an overriding method can allow more, but not less, access than the overridden method.
Final methods cannot be overridden: If we don’t want a method to be overridden, we declare it as final.
Static methods cannot be overridden: When you define a static method with the same signature as a static method in the base class, it is known as method hiding.